﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using TalksLog.Abstraction.Services;
using TalksLog.UI.Common;
using TalksLog.UI.Models.APIModels;

namespace TalksLog.UI.API
{
    [Authorize]
    [Route("api/[controller]")]
    [ApiController]
    public class AccountController : ControllerBase
    {
        private AccountServiceBase _service;

        public AccountController(AccountServiceBase service)
        {
            _service = service;
        }
        
        [HttpGet("ok")]
        public string OK()
        {
            return "OK";
        }

        [HttpPost("change_password")]
        public ActionResult<bool> ChangePassword([FromForm]int id, [FromForm]string oldPassword, [FromForm]string newPassword)
        {
            return _service.ChangePassword(id, oldPassword, newPassword);
        }

        [HttpPost("change_name")]
        public ActionResult<APIBoolResult> ChangeName([FromForm]int id, [FromForm]string newName)
        {
            string message = null;
            bool result = _service.ChanageName(id, newName, out message);
            if (result)
            {
                this.LoginAgain(newName);
            }
            
            return new APIBoolResult { IsSuccess = result, Message = message };
        }

        private void LoginAgain(string newName)
        {
            string accountId = HttpContext.User.Claims.First(c => c.Type == ClaimTypes.NameIdentifier).Value;
            string email = HttpContext.User.Claims.First(c => c.Type == ClaimTypes.Email).Value;
            string gender = HttpContext.User.Claims.First(c => c.Type == ClaimTypes.Gender).Value;
            string registerDate = HttpContext.User.Claims.First(c => c.Type == ClaimTypesExt.RegisterDate).Value;

            var claims = new Claim[]
            {
                new Claim(ClaimTypes.NameIdentifier, accountId),
                new Claim(ClaimTypes.Name, newName),
                new Claim(ClaimTypes.Email, email),
                new Claim(ClaimTypes.Gender, gender),
                new Claim(ClaimTypesExt.RegisterDate, registerDate),
            };

            var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
            var principal = new ClaimsPrincipal(identity);

            HttpContext.SignOutAsync();
            HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
        }
    }
}